import { hashHistory } from 'dva/router';

import zhCN from 'antd/es/locale/zh_CN';
import enUS from 'antd/es/locale/en_US';
import en from 'react-intl/locale-data/en';
import zh from 'react-intl/locale-data/zh';

import request from 'umi-request';

/**
 * 获取远程的i18n资源
 * @param localeFlag
 * @return {Promise<any>}
 */
async function loadRemoteI18nMessages({ localeFlag }) {
  return request.get(`/i18n-data/${localeFlag}.json`)
}

const defaultLocale = 'zhCN'
const antdI18nMap = {
  zhCN: zhCN,
  enUS: enUS,
}
const IntlI18nMap = {
  zhCN: {
    key: 'zh',
    data: zh
  },
  enUS: {
    key: 'en',
    data: en
  }
}

export default {
  namespace: 'GlobalModel',

  state: {
    selectedLocaleFlag: defaultLocale,
    // 应用的国际化资源(从后台加载)
    appLocaleMessage: {},
    appLocaleData: IntlI18nMap[defaultLocale],
    // ant design组件的国际化资源(组件自带)
    antdLocale: antdI18nMap[defaultLocale],
    localeList: [{
      code: 'zhCN',
      name: '中文'
    }, {
      code: 'enUS',
      name: '英文'
    }]
  },

  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由变化
      history.listen(location => {
        if (location.pathname === '/index') {
          dispatch({
            type: 'query'
          })
        }
      });
    },
  },

  effects: {
    /**
     *
     * @param localeFlag 选择的语言标识
     * @param select 用于获取指定dva model的state
     * @param call 用于发起对自定义函数的调用
     * @param put 用于发起对dva reducer 方法的调用
     * @return {IterableIterator<*>}
     */* query({ localeFlag }, { select, call, put }) {
      const realLocaleFlag = localeFlag ? localeFlag : yield select(status => status.GlobalModel.selectedLocaleFlag)
      const i18nMessages = yield call(loadRemoteI18nMessages, { localeFlag: realLocaleFlag })
      yield put({
        type: 'changeLocal',
        localeFlag: realLocaleFlag,
        appLocaleMessage: i18nMessages
      })
    }
  },
  reducers: {
    /*
    * 改变区域语言
    */
    changeLocal(state, { localeFlag, appLocaleMessage }) {
      return {
        ...state,
        selectedLocaleFlag: localeFlag,
        appLocaleMessage,
        antdLocale: antdI18nMap[localeFlag],
        appLocaleData: IntlI18nMap[localeFlag]
      }
    }
  }
}
